package com.ppyydd.sms.servlets;


import com.ppyydd.sms.beans.Student;
import com.ppyydd.sms.service.IStudentService;
import com.ppyydd.sms.service.StudentServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //1.获取传递的参数。
        String num = request.getParameter("num").trim();
        String password = request.getParameter("password").trim();
        HttpSession session = request.getSession();
        //2.创建Service对象
        IStudentService service = new StudentServiceImpl();
        if (num == null || "".equals(num)) {
            session.setAttribute("information", "学号输入有误！");
            response.sendRedirect(request.getContextPath() + "/login.jsp");//请求转发会出现恶意刷新，所以采用重定向
            return;
        }
        if (password == null || "".equals(password)) {
            session.setAttribute("information", "密码输入有误");
            response.sendRedirect(request.getContextPath() + "/login.jsp");//请求转发会出现恶意刷新，所以采用重定向
            return;
        }
        //3.调用Service对象的checkUser()方法对用户进行验证
        Student student = service.checkUser(num, password);
        //4.验证未通过，则跳转到登录页面，让用户再次输入登录信息。此时页面需要给出用户一些提示
        if (student == null) {
            session.setAttribute("information", "用户名或者密码输入有误");
            response.sendRedirect(request.getContextPath() + "/login.jsp");//请求转发会出现恶意刷新，所以采用重定向
            return;
        }
        //4.验证通过，跳转到系统主页index.jsp。
        response.sendRedirect(request.getContextPath() + "/index.jsp");//请求转发会出现恶意刷新，所以采用重定向

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doPost(request, response);
    }
}
